/**
 * 页面装修的服务
 */

'use strict';

// 表名
const COLLECTION_NAME = "me-page-design"
// 状态码
const CODE_SUCCESS = {code:200, msg:"成功"}
const CODE_NO_SERVICE = {code:404, msg:"未找到相关服务"}
const CODE_NAME_EXIST = {code:3001, msg:"页面的别名已存在"}

exports.main = async (e, ctx) => {
	// 拦截器
	let result = CODE_SUCCESS
	
	switch (e.method){
		case "add": // 新增
			if(e.param.name){
				let isAdd = await detail(e.param)
				if(isAdd.data[0]){
					result.code = CODE_NAME_EXIST.code
					result.msg = CODE_NAME_EXIST.msg + ": " + e.param.name
					break;
				}
			}
			result.data = await add(e.param)
			break;
		case "list": // 列表
			result.data = await list(e.param)
			break;
		case "detail": // 详情
			let resDetail = await detail(e.param)
			if (resDetail.data.length>1) {
				result.data = resDetail.data // 列表
			} else{
				result.data = resDetail.data[0] // 详情
			}
			break;
		case "update": // 更新
			result.data = await update(e.param)
			break;
		case "del": // 删除
			result.data = await del(e.param)
			break;
		default:
			result.code = CODE_NO_SERVICE.code
			result.msg = CODE_NO_SERVICE.msg + ": " + e.method
			break;
	}
	return result
}

// 新增记录
function add(param){
	param.time_add = Date.now() // 加入服务器时间
	param.time_update = Date.now() // 加入服务器时间
	return getCollection().add(param)
}

// 查询列表
function list(param){
	return new Promise(async resolve=>{
		let pageNum = param.pageNum || 1
		let pageSize = param.pageSize || 10
		let skip = (pageNum - 1) * pageSize
		const db = uniCloud.database()
		const dbCmd = db.command
		let andWhere = []
		// if(param.keyword){ // 关键词搜索
			let reg = new RegExp(param.keyword);
			andWhere.push(dbCmd.or({title: reg},{name: reg}))
		// }
		let res = await getCollection(db).where(dbCmd.and(andWhere)).skip(skip).limit(pageSize).orderBy("_id", "desc").get()
		let totalInfo = await getCollection(db).where(dbCmd.and(andWhere)).count()
		res.affectedDocs = totalInfo.total;
		resolve(res)
	})
}

// 详情
function detail(param){
	const db = uniCloud.database()
	const dbCmd = db.command
	let where = {}
	if(param._id){
		where._id = param._id
	}else if(param.name){
		where.name = param.name
	}
	return getCollection(db).where(where).get()
}

// 更新
function update(param){
	let _id = param._id
	delete param["_id"] // 不可更新_id字段
	param.time_update = Date.now() // 加入服务器时间
	return getCollection().doc(_id).update(param)
}

// 删除
function del(param){
	return getCollection().doc(param._id).remove()
}

// 读表
function getCollection(db){
	if(!db) db = uniCloud.database()
	return db.collection(COLLECTION_NAME)
}